package com.soft.zosagent.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @description: 类文件加密工具
 * @author: cinbo，chenyinbo
 * @create: 2020-12-04 16:19
 */
public class ClassEncryptUtil {

    public static native int encryptData(byte[] indata,int length,byte[] outdata);
    public static native int decryptData(byte[] indata,int length,byte[] outdata);
    static{
        //System.out.println(System.getProperty("java.library.path"));
        System.loadLibrary("EncryptUtil");
    }

    public static void encryptFile(File classFile) throws Exception{

        if(classFile.isDirectory()){
            encryptDir(classFile);
            return;
        }
        if(!classFile.getPath().endsWith(".class")){
            return;
        }
        System.out.println("encrypt file:"+classFile.getPath());
        byte[] infileBytes  = new byte[1024 * 1024 * 10];
        byte[] outfilebytes = new byte[1024 * 1024 * 10];

        FileInputStream in = new FileInputStream(classFile);

        int actualBytsLen = in.read(infileBytes);
        in.close();
        int outlen = encryptData(infileBytes,actualBytsLen,outfilebytes);
        FileOutputStream out = new FileOutputStream(classFile);
        out.write(outfilebytes,0,outlen);
        out.close();
    }

    private static void encryptDir(File classFile) throws Exception{

        File[]  fileList = classFile.listFiles();
        for(File file:fileList){
            if(file.isDirectory()){
                encryptDir(file);
            }else if (file.isFile()){
                encryptFile(file);
            }else{
                System.out.println("not support type.");
            }

        }

    }

    public static void decryptFile(String classFileName) throws Exception{
        byte[] infileBytes  = new byte[1024 * 1024 * 10];
        byte[] outfilebytes = new byte[1024 * 1024 * 10];

        FileInputStream in = new FileInputStream(classFileName);

        int actualBytsLen = in.read(infileBytes);
        in.close();
        int outlen = decryptData(infileBytes,actualBytsLen,outfilebytes);
        FileOutputStream out = new FileOutputStream(classFileName);
        out.write(outfilebytes,0,outlen);
        out.close();
    }

    public static void main(String[] args) throws Exception {

       String classFileName = args[1];

        if(args[0].equals("1")){
           encryptFile(new File(classFileName));
       }
       if(args[0].equals("2")){
           decryptFile(classFileName);
       }

    }



}
